import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

subject = "Python邮件测试"
body = "你好，这是一个测试邮件！"
sender = "m18503090587@163.com"
license_code = "EQg93sCjETcqJbuz"
receivers = ["m18503090587@163.com"]

def send_email(subject, body, sender, license_code, receivers, smtp_host="smtp.163.com", smtp_port=25):
    try:
        # 创建一个带附件的实例
        mm = MIMEMultipart('related')

        # 设置邮件主题
        mm["Subject"] = Header(subject, 'utf-8')
        # 设置发送者
        mm["From"] = sender
        # 设置接受者
        mm["To"] = ", ".join(receivers)

        # 邮件正文内容
        body_content = body
        # 构造文本, 参数1：正文内容，参数2：文本格式，参数3：编码方式
        message_text = MIMEText(body_content, "plain", "utf-8")
        # 向MIMEMultipart对象中添加文本对象
        mm.attach(message_text)

        # 创建SMTP对象
        stp = smtplib.SMTP()
        # 设置发件人邮箱的域名和端口，端口地址为25
        stp.connect(smtp_host, smtp_port)
        # set_debuglevel(1)可以打印出和SMTP服务器交互的所有信息
        stp.set_debuglevel(1)
        # 登录邮箱，传递参数1：邮箱地址，参数2：邮箱授权码
        stp.login(sender, license_code)
        # 发送邮件，传递参数1：发件人邮箱地址，参数2：收件人邮箱地址，参数3：把邮件内容格式改为str
        stp.sendmail(sender, receivers, mm.as_string())
        print("邮件发送成功")
        # 关闭SMTP对象
        stp.quit()
    except Exception as e:
        print(f"发送邮件时发生错误: {e}")


# 示例使用
if __name__ == "__main__":
    send_email(subject, body, sender, license_code, receivers)